var Promise = require('bluebird');
var Station = require('mongoose').model('Station');
var Config = require('mongoose').model('Config');
var LabelInfo = require('mongoose').model('Label');
var HistoryInfo = require('mongoose').model('StationHistory');

function saveHistory(id, updateId, history, cb) {
    var info = {id: id, nodeID: updateId, updateDate: new Date().getTime()};
    // if (result.length === 0) {
    info.beforeUpdateInfo = history.beforeUpdate;
    info.afterUpdateInfo = history.afterUpdate;
    HistoryInfo.create(info, function (err, data) {
        if (err) {
            console.log(err);
            return cb('记录历史失败')
        }
        cb(data)
    });
}

function createStation(station, defer) {
    Station.create(station, function (err, stationData) {
        if (err) {
            return defer.reject('创建失败')
        }
        Config.where().exec(function (err, config) {
            var stationInfo = [{rtk_bases: config[0].rtk_bases, uwb_bases: config[0].uwb_bases}];

            if (station.nodeType !== "UWB") {
                stationInfo[0].rtk_bases.push(station.nodeID)
            } else {
                stationInfo[0].uwb_bases.push(station.nodeID)
            }
            Config.update({test: 0}, stationInfo[0]).exec(function (err, data) {
                if (err) {
                    console.log(err)
                    return defer.reject('update error')
                } else {
                    saveHistory(stationData._id, stationData.nodeID, {
                        beforeUpdate: null,
                        afterUpdate: stationData
                    }, function () {
                        defer.resolve({status: true, message: stationData})
                    });
                }
            })
        });
    })
}

function saveDelHistory(id, updateId, cb) {
    var info = {id: id, nodeID: updateId, updateDate: new Date().getTime(), delete: true};

    HistoryInfo.create(info, function (err, data) {
        if (err) {
            console.log(err);
            return cb({status: false, message: '记录历史失败'})
        }
        cb({status: true, message: data})
    });
}

function removeConfig(dataId, id, defer) {
    Config.where().exec(function (err, data) {
        var stationInfo = [{rtk_bases: data[0].rtk_bases, uwb_bases: data[0].uwb_bases}];
        var rtk = stationInfo[0].rtk_bases.indexOf(id);
        var uwb = stationInfo[0].uwb_bases.indexOf(id);
        if (rtk > -1) {
            stationInfo[0].rtk_bases.splice(rtk, 1);
        }
        if (uwb > -1) {
            stationInfo[0].uwb_bases.splice(uwb, 1);
        }
        console.log(stationInfo)
        Config.update({test: 0}, stationInfo[0]).exec(function (err, data) {
            if (err) {
                console.log(err);
                return defer.reject('update error')
            } else {
                saveDelHistory(dataId, id, function (result) {
                    defer.resolve({status: true})
                })
            }
        })
    });
}

module.exports = {
    update: function (query, info, history) {
        var defer = Promise.defer();
        Station.where({$or: [{nodeID: info.nodeID}]}).exec()
            .then(function (result) {

                LabelInfo.where({$or: [{nodeID: info.nodeID}]}).exec()
                    .then(function (label) {

                        if ((result.length === 0 || (result.length === 1 && info.nodeID == query.nodeID)) && label.length === 0) {
                            Station.update(query, info).exec(function (err, data) {
                                if (err) {
                                    return defer.reject('update error')
                                } else {
                                    history.afterUpdate = info;
                                    Station.findOne({nodeID: info.nodeID}).exec(function (err, data) {
                                        if (err) {
                                            return defer.reject('get station error')
                                        }
                                        saveHistory(data._id, info.nodeID, history, function (data) {
                                            defer.resolve({status: true, message: data})
                                        });
                                    })
                                }
                            })
                        } else {
                            defer.resolve({status: false, message: 'id 已存在'})
                        }
                    })
            })
        return defer.promise
    },
    delete: function (id) {
        var defer = Promise.defer();
        Station.findOne({nodeID: id}).exec(function (err, data) {
            if (err) {
                return defer.reject('delete station error')
            }
            if (!data) {
                return defer.resolve({status: false, message: 'station not exist'})
            } else {
                var dataId = data._id;
                data.remove(function (err) {
                    removeConfig(dataId, id, defer)
                })
            }
        });
        return defer.promise
    },
    all: function () {
        var defer = Promise.defer();
        Station.where().exec(function (err, data) {
            if (err) {
                defer.reject('find all station error')
            } else {
                defer.resolve(data)
            }
        });
        return defer.promise
    },
    findByType: function (type) {
        var defer = Promise.defer();
        Station.where({nodeType: Number(type)}).exec(function (err, data) {
            if (err) {
                defer.reject('find all station error')
            } else {
                defer.resolve(data)
            }
        });
        return defer.promise
    },
    create: function (station) {
        var defer = Promise.defer();
        Station.where({$or: [{nodeID: station.nodeID}]}).exec()
            .then(function (result) {

                LabelInfo.where({$or: [{nodeID: station.nodeID}]}).exec()
                    .then(function (label) {

                        if (result.length === 0 && label.length === 0) {
                            // station.nodeType = station.nodeType === 'UWB' ? 1 : 2;
                            createStation(station, defer);
                        } else {
                            defer.resolve({status: false, message: '基站已存在'})
                        }
                    })
            });
        return defer.promise
    }
};